package net.lovesrc.allin.biz.ocr;

import com.alibaba.fastjson.JSONObject;
import com.zhouzhou.fastjava.http.Requests;
import net.lovesrc.allin.biz.BaseService;
import net.lovesrc.allin.biz.idcard.IdCardService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class OcrService extends BaseService {

    public JSONObject idCard(File img, String side) {
        try {
            JSONObject resJson = Requests.post("https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + getBaiduYunAccessToken())
                    .param("detect_direction", "true")
                    .param("id_card_side", side)
                    .param("image", Base64Utils.encodeToString(FileUtils.readFileToByteArray(img)))
                    .execute()
                    .asJson();
            return resJson;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject generalBasic(File img) {
        try {
            JSONObject resJson = Requests.post("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + getBaiduYunAccessToken())
                    .param("image", Base64Utils.encodeToString(FileUtils.readFileToByteArray(img)))
                    .execute()
                    .asJson();
            return resJson;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String getBaiduYunAccessToken() {
        String accessToken = redisTemplate.opsForValue().get("BAIDU_YUN_ACCESS_TOKEN");
        if (StringUtils.isBlank(accessToken)) {
            JSONObject resJson = Requests.post("https://aip.baidubce.com/oauth/2.0/token")
                    .param("grant_type", "client_credentials")
//                    .param("client_id", "m0zO4zTWa0MhVtfYpIPm2an5")
//                    .param("client_secret", "zot8nuCrPbCKD3URS22yFQ4DeTWKr4iy")
                    .param("client_id", "BpBb2hBYjz4LXkn3ZzBdKlrv")
                    .param("client_secret", "ZYXXjtCd3oHSGRVZA3zPjkIL273bV3oN")
                    .execute()
                    .asJson();
            accessToken = resJson.getString("access_token");
            long expiresInSeconds = resJson.getLongValue("expires_in");
            redisTemplate.opsForValue().set("BAIDU_YUN_ACCESS_TOKEN", accessToken, expiresInSeconds - 300, TimeUnit.SECONDS);
        }
        return accessToken;
    }


    public static void main(String[] args) {
        File file =new File(IdCardService.TMP_ROOT+"\\14232619920618302X","1.jpg");
        OcrService ocrService =new OcrService();
        JSONObject jsonObject = ocrService.idCard(file, "front");
        System.out.println(jsonObject);
    }
}
